package com.telit.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.telit.common.util.LanguageUtils;
import com.telit.common.entity.DataReturn;
import com.telit.common.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * 文件上传拦截器
 *
 * @author yuezhuang
 * @date 2022-10-21
 */
@Slf4j
@Component
public class FileInterceptor implements HandlerInterceptor {

    @Value("${forest.file.extensionPermit:jpg,png,jpeg,gif,wep,bmp,doc,docx,ppt,pptx,xls,xlsx,pdf,mp4,wav,avi,mp3}")
    private String fileExtensionPermit;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 判断是否为文件上传请求
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartReq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> files = multipartReq.getFileMap();

            for (String formKey : files.keySet()) {
                MultipartFile file = multipartReq.getFile(formKey);
                // 后缀名文件类型
                String filename = file.getOriginalFilename();
                String suffixType = StringUtils.substringAfterLast(filename, ".");
                // 判断是否允许的文件后缀名
                if (!fileExtensionPermit.contains(suffixType.toLowerCase())) {
                    DataReturn dataReturn = DataReturn.failure(ResultCode.FILE_TYPE_ERROR.getCode(),
                            LanguageUtils.codeMessage(ResultCode.FILE_TYPE_ERROR.getCode(), fileExtensionPermit));

                    log.error("上传文件后缀校验失败：{}", JSON.toJSONString(dataReturn));

                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.getWriter().write(JSON.toJSONString(dataReturn));
                    response.flushBuffer();
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
